package com.syyo.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.syyo.common.to.es.SkuEsModel;
import com.syyo.gulimall.search.config.GulimallElasticsearchConfig;
import com.syyo.gulimall.search.constant.EsConstant;
import com.syyo.gulimall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: wang
 * @date: 2021/3/24 15:50
 * @Description:
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private RestHighLevelClient esClient;


    @Override
    public boolean add(List<SkuEsModel> list) throws IOException {
        // 保存到es
        // 1.建立索引库
        // 2.保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel esModel : list) {
            // 构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDE);
            indexRequest.id(esModel.getSkuId().toString());
            String s = JSON.toJSONString(esModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);

        }

        BulkResponse bulk = esClient.bulk(bulkRequest, GulimallElasticsearchConfig.COMMON_OPTION);

        // 请求状态，返回的b是true表示有错误
        boolean b = bulk.hasFailures();
        BulkItemResponse[] items = bulk.getItems();

        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());

        log.info("商品上架完成：{},返回状态,{}", collect, b);

        return b;
    }
}
